#!/bin/bash

init_begin_date='2022-10-01'
init_stop_date='2023-06-14'
add_days=30
date_format='+%Y-%m-%d'

CK_HOST='127.0.0.1'
CK_USER='default'
CK_PWD='123456'
CK_PORT=9000
OUTDIR=$(pwd)

EXPORT_TABLE='marmot_point.xmp_track_base_new'


DATA_RESULT_DB=$OUTDIR/result
mkdir -p $DATA_RESULT_DB

while true
do
  if [ $end_date ];then
    start_date=$end_date
  else
    start_date=$init_begin_date
  fi
  end_date=$(date -d "${start_date} ${add_days} days" "${date_format}")
  #echo "-- ${start_date}   -- ${end_date}"
  if [[ $end_date > "$init_stop_date" ]];then
     end_date=$init_stop_date
  fi
  echo "clickhouse-client -h $CK_HOST -u $CK_USER --password=\"${CK_PWD}\" --port=${CK_PORT} -q \"select * from ${EXPORT_TABLE} where server_time >= '${start_date}' and server_time < '${end_date}' FORMAT CSVWithNames\"  --format_csv_delimiter=',' > ${DATA_RESULT_DB}/${EXPORT_TABLE}.${start_date}-${end_date}.csv"
  clickhouse-client -h $CK_HOST -u $CK_USER --password="${CK_PWD}" --port=${CK_PORT} -q "select * from ${EXPORT_TABLE} where server_time >= '${start_date}' and server_time < '${end_date}' FORMAT CSVWithNames"  --format_csv_delimiter=',' > ${DATA_RESULT_DB}/${EXPORT_TABLE}.${start_date}-${end_date}.csv
  sleep 1
  if [[ $end_date = "$init_stop_date" ]];then
    #echo "==== ${start_date}   ==== ${end_date}" 
    exit 1
  fi
done
